<template>
  <div class="reportMistakeInfoAction el-card is-always-shadow el-card__body">
    <avue-crud
      ref="crud"
      :option="option"
      :table-loading="listLoading"
      :data="tableData"
      :page.sync="page"
      :search.sync="searchForm"
      :row-style="rowStyle"
      @search-change="handleFilter"
      @selection-change="selectionChange"
      @refresh-change="search"
      @on-load="search">
      <template slot="menuRight">
        <!--        <el-button type="primary" size="mini" @click="updateReportPromise()">报表编辑权限设置</el-button>-->
        <el-button type="primary" size="mini" @click="exportExcel">导出</el-button>
      </template>
      <template slot="search" slot-scope="{row,size}">
        <el-form-item label="申请时间">
          <el-date-picker
            :size="size"
            v-model="searchForm.applyTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报表时间">
          <el-date-picker
            :size="size"
            v-model="searchForm.reprotTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="报表时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改状态">
          <el-select
            :size="size"
            v-model="searchForm.isModify"
            type="select"
            placeholder="修改状态">
            <el-option value="1" label="已完成"></el-option>
            <el-option value="0" label="待修改"></el-option>
          </el-select>
        </el-form-item>
      </template>
      <template slot-scope="scope" slot="reportNameSearch">
        <el-select v-model="searchForm.reportNameId" placeholder="请选择" style="width: 150px" >
          <el-option
            v-for="(item,index) in reportNameIds"
            :key="index"
            :label="item.reportName"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template slot="searchMenu" slot-scope="{row,size}">
        <el-button :size="size" @click="()=>{setSearchFiledsEmpty(row);setSearchFiledsEmpty(searchForm);search()}" icon="el-icon-delete">清空</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" v-if="scope.row.isModify!='1' && (moment(scope.row.noticeTime).add(Number(scope.row.modifyLimitTime),'days'))>=moment()" plain @click.stop="updateReport(scope.row)">修改报表</el-button>
        <el-button type="text" size="small" plain @click.stop="preview(scope.row,2,'预览')">预览</el-button>
        <!-- <el-button type="text" v-if="scope.row.isModify!='1'" size="small" plain @click.stop="editorContent(scope.row,4,'编辑')">编辑</el-button> -->
        <el-button type="text" v-if="(moment(scope.row.noticeTime).add(Number(scope.row.modifyLimitTime),'days'))>=moment()" size="small" plain @click.stop="editorContent(scope.row,4,'编辑')">编辑</el-button>
      </template>
    </avue-crud>
    <!--    <report-mistake-info-editor ref="reportMistakeInfoEditor" v-if="isShowReportMistakeInfoEditor"></report-mistake-info-editor>-->
    <Editor ref="Editor" ></Editor>
    <PREVIEW ref="preview" ></PREVIEW>
  </div>
</template>


<script>
  import {getForm, postForm} from '@/api/gen/gen'
  import Editor from './Editor';
  import PREVIEW from './pre.vue';

  import ExportJsonExcel from "js-export-excel";
  import moment from 'moment';
  import {
    approveStatus, getApproveStatus,
    getgetStationCodes,
    getLineCodes, getMappingStatus, getStationByCode, getLineAndStationByCode, getSwPmReportPath, numToTwoPoint, setSearchFiledsEmpty
  } from "../../../../../api/subwayRat/commonCheck";
  import {
    get_xw_ReportErrorList, get_xw_ReportInfos, update_xw_ReportInfos,
    update_xw_ReportPromise
  } from "../../../../../api/stationTiecketManager/xianWngCJXXQR/BBCCGG/XWBBCCGGTZ/KZDLCK";
  import {exportDataToExcel} from "../../../../../api/subwayRat/exportSelf";
  import transitUtil from "@/api/subwayRat/transitUtil";
  import { dateFormat } from "@/util/date";
  export default {
    components:{
      Editor,PREVIEW
    },
    data() {
      return {
        row : {},
        listLoading: true,
        fileTemp:{},
        searchForm:{
          lineCode:'',
          stationCode:''
        },
        tableData:[],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条,
          isAsc: false// 是否倒序
        },
        autoWidth: true,
        downloadLoading: false,
        isShowReportMistakeInfoEditor:false,//是否加载编辑页面
        multipleSelectionRows:[],
        multipleSelectionKeys:[],
        lineCodes:[],
        stationCodes:[],
        reportNameIds:[],
        param:{
          lineCode:"",
          stationCode:'',
          reprotTime:"",
          reportNameId:"",
          settleBeginTime:"",
          settleEndTime:""
        },
        option:{
          emptyBtn:false,
          editBtn:false,
          delBtn:false,
          addBtn:false,
          border: true,
          stripe: true,
          index:true,
          indexLabel:'序号',
          page:true,
          align:'center',
          menuWidth:150,
          menuAlign:'center',
          selection: true,
          reserveSelection:true,
          height: 450,
          column:[
            // {prop:"lineName", label:"线路",search:false},
            // {prop:"stationName", label:"车站",search:false},
            // {prop:"noticeTime" ,label:"通知时间"},
            {prop:"applyTime" ,label:"申请时间",width: 90,format:'yyyy-MM-dd',formatter:function (row,v) {
                return moment(v).format('YYYY-MM-DD');
              }},
            {prop:"reprotTime", label:"报表时间",width: 90},
            {prop:"errorClassification",label:"差错类别",search:'true',type:'select',
              dicUrl: '/admin/dict/type/ERROR_CLASSIFICATION',
              formatter:function (row,v) {
                return getMappingStatus('ERROR_CLASSIFICATION',v);
              }
            },
            {prop:"tvmCode", label:"TVM编号"},
            {prop:"bomCode", label:"BOM编号"},
            {prop:"deviceNo", label:"设备操作号",width: 90},
            {prop:"equipmentCode", label:"互联网购票机编号",hide: true,width: 120},
            {prop:"applyReason", label:"差异原因",width: 160},
            // {prop:"errorAmount", label:"差异金额",formatter:function (row,v) {
            //     return numToTwoPoint(v);
            //   }},
            {prop:"reportName",label:"报表名称",search:true,searchslot:true,width: 90},
            {prop:"dataSource", label:"数据来源", search:'true',type:'select',
              dicUrl: '/admin/dict/type/report_error_data_source',
              formatter:function (row,v) {
                return getMappingStatus('report_error_data_source',v);
              }
              // dicData: [{
              //   label: '车站申请',
              //   value: '1'
              // }, {
              //   label: '线网手工录入',
              //   value: '2'
              // },{
              //   label: '售票员票款差异',
              //   value: '3'
              // },{
              //   label: 'TVM票款差异',
              //   value: '4'
              // },{
              //   label: '分钱箱票款差异',
              //   value: '5'
              // },{
              //   label: '乘客事务审核',
              //   value: '6'
              // },{
              //   label: '乘客事务-其他相关数据录入',
              //   value: '7'
              // },{
              //   label: '乘客事务审核（即时退换票）',
              //   value: '8'
              // },{
              //   label: '乘客事务审核（非即时退换票）',
              //   value: '9'
              // },{
              //   label: '营销车票审核',
              //   value: '10'
              // },{
              //   label: '票卡信息审核差异',
              //   value: '11'
              // },{
              //   label: '互联网售票机',
              //   value: '12'
              // }]
            },
            {prop:"checkStatus", label:"审批状态",type:'select',search:true,dicData:approveStatus(),formatter:function(row,value){
                return getApproveStatus(value);
              }},
            {prop:"modifyLimitTime", label:"修改期限(天)",width: 100},
            {prop:"lastTime", label:"最晚修改日期",width: 100,formatter:function (row,v) {
                return moment(row.noticeTime).add(Number(row.modifyLimitTime),'days').format('YYYY-MM-DD');
              }},
            // {prop:"dutyStationLeaderName", label:"值班站长"},
            // {prop:"dutyStationPersonName" ,label:"值班员"},
            // {prop:"stationPersonName", label:"站务员"},
            // {prop:"errorDetail" ,label:"错误详情"},
            {prop:"modifyTime", label:"更改日期",width: 90,format:'yyyy-MM-dd',
              // formatter:function (row,v) {
              //   return moment(v).format('YYYY-MM-DD');
              // }
            },
            {prop:"isModify", label:"修改状态",
                dicData: [{
                  label: '待修改',
                  value: '0'
                }, {
                  label: '已完成',
                  value: '1'
                }],
                formatter:function(row, value , label, column){
                  return value==0?'待修改':value==1?'已完成':'';
                }
            },
            {prop:"remark" ,label:"备注",width: 150},
            // {prop:"creatorName", label:"更改人"},
            // {prop:"creatorName1", label:"报表编辑权限"},
            {prop:"creatorName" ,label:"申请人"},
            {prop:"creatorCode", label:"申请人员工号",width: 100},
            {prop:"noticePerson" ,label:"通知人",width: 100},
            {prop:"noticePersonCode" ,label:"通知人工号",width: 100,hide: true}
          ]
        },
      }
    },
    created() {
      if(this.$route.query.row){
        this.row = this.$route.query.row;
        debugger
        if(!this.row.submitLineCode && ! this.row.submitStationCode){
          this.row.submitLineCode = this.row.lineCode;
          this.row.submitStationCode = this.row.stationCode;
        }
        this.addContent('添加',0);
      }
    },
    methods: {
      moment,setSearchFiledsEmpty,
      updateReportPromise(){
        update_xw_ReportPromise().then(res=>{

        })
      },
      handlePreview(file){
        alert("successFun")
      },
      rowStyle({ row, column, rowIndex }) {
        let now = dateFormat(new Date()).substr(0, 10);
        let lastTime = moment(row.noticeTime).add(Number(row.modifyLimitTime),'days').format('YYYY-MM-DD');
        if (row.isModify == '0' && lastTime<now) {
          return {
            backgroundColor: "#eee",
            color: "red",
          };
        }
      },
      async exportData(){ // 导出
        this.searchForm.pageNo=1;
        this.searchForm.pageSize=1000000000;
        if(this.selectKeys.length>0){
          exportDataToExcel(this.selectKeys,this.option.column,'线网报表差错更改通知');
        }else {
          let res=await get_xw_ReportErrorList(this.searchForm);
          let data = res.data.data;
          exportDataToExcel(data,this.option.column,'线网报表差错更改通知');
        }
      },
      search(){
        Object.assign(this.searchForm,this.page);
        this.searchForm.userCode=this.$store.getters.userInfo.userCode;
        if(!this.$store.getters.userInfo.belongToLine){
          this.searchForm.lineCode = this.$store.getters.userInfo.lineCode;
          this.searchForm.stationCode = this.$store.getters.userInfo.stationCode;
        }
        this.searchForm.noticeStatus = 1;
        get_xw_ReportErrorList(this.searchForm).then((res)=>{
          this.tableData=res.data.data;
          this.listLoading = false;
          this.page.total=res.data.total;
        });
      },
      delData() {
        if(this.multipleSelectionKeys.length<=0){
          this.$message({
            message: '请选择操作项！',
            type: 'warning'
          });
          return;
        }
        this.$confirm('您是否要删除此数据？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          delReportError({ids:this.multipleSelectionKeys.join(","),delFlag:1}).then((res)=>{
            this.$message({
              message: res.data.code==0?'操作成功':'操作失败',
              type: res.data.code==0?'success':'error',
            });
            this.search();
          });
        }).catch(() => {
        });
      },
      preview(row,showType,title){
        this.$nextTick(()=>{
          this.$refs.preview.previewEditor(row,showType,title);
        });
      },
      editorContent(row,showType,title){
        this.$nextTick(()=>{
          this.$refs.Editor.previewEditor(row,showType,title);
        });
      },
      updateReport(row){ //修改报表
        get_xw_ReportInfos({reportId:row.reportNameId,id:row.id}).then(res=>{
          if(res.data.code==0){
            update_xw_ReportInfos({reportId:row.reportNameId,id:row.id,
              reportSQXGId:row.id,
              lineCode:row.lineCode,stationCode:row.stationCode,reportDate:row.reprotTime,
              dataSource:row.dataSource,tvmCode:row.tvmCode,stationPersonCode:res.data.data.stationPersonCode,
              bomCode:row.bomCode,deviceNo:row.deviceNo,cashboxType:row.cashboxType,
              settleBeginTime:row.settleBeginTime,settleEndTime:row.settleEndTime,equipmentCode:row.equipmentCode,cardNo:row.cardNo}).then(res2=>{
              if(res2.data.code==0){
                this.$router.push({path:res2.data.data.reportPath});
              }
              setTimeout(function () {
                transitUtil.$emit("updateReport_call_"+row.reportNameId, res2.data.data.param);
              }, 1000)
            })
          }
        })
      },
      handleSelectionChange(val,a){
        this.multipleSelectionRows=val;
        this.multipleSelectionKeys=[];
        for(let i=0;i<this.multipleSelectionRows.length;i++){
          this.multipleSelectionKeys.push(this.multipleSelectionRows[i].id);
        }
      },
      initLine(){
        getLineCodes().then(res=>{ //获取线路
          this.lineCodes=res;
        });
      },
      initReportNameIds(){
        getSwPmReportPath({}).then((res)=>{
          this.reportNameIds=res.data.data;
        })
      },
      changeLine(v){
        getgetStationCodes(v).then(res=>{
          this.stationCodes=res;
          this.searchForm.stationCode='';
        })
      },
      async noticeReport(){

        if(this.multipleSelectionKeys.length<=0){
          this.$message({
            message: '您至少选择一条或多条信息发送通知！',
            type: 'warning'
          });
          return;
        }
        let messageLSList = [];
        for(let i=0;i<this.selectKeys.length;i++){
          let data = await getLineAndStationByCode({"lineCode":this.selectKeys[i].lineCode, "code":this.selectKeys[i].stationCode});
          messageLSList.push({
            "content":"车站：" + data.data[0].name,
            "lineCode":this.selectKeys[i].lineCode,
            "stationCode":this.selectKeys[i].stationCode
          })
        }
        let p = {
          messageLSList:JSON.stringify(messageLSList),
          title:this.$store.getters.tag.label,
          msgType:"通知",
          type:"reportMistakeInfo_001",
          ids:this.multipleSelectionKeys,
          noticeStatus:1
        };
        this.$confirm('您是否要通知此数据？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          noticeReport(p).then((res)=>{
            this.$message({
              message: res.data.code==0?'操作成功':'操作失败',
              type: res.data.code==0?'success':'error',
            });
            this.search();
          });
        }).catch(() => {
        });
      },
      async exportExcel(){ // 导出
        let p={};
        Object.assign(p,this.searchForm);
        p.pageNo=1;
        p.pageSize=1000000000;
        if(this.multipleSelectionRows.length>0){
          let newData = JSON.parse(JSON.stringify(this.multipleSelectionRows));
          exportDataToExcel(newData,this.option.column,'线网报表差错更改通知-客值');
        }else {
          let res=await get_xw_ReportErrorList(p);
          let data = res.data.data;
          exportDataToExcel(data,this.option.column,'线网报表差错更改通知-客值');
        }
      },
      selectionChange(list){
        this.multipleSelectionRows=list;
        this.multipleSelectionKeys=[];
        for(let i=0;i<list.length;i++){
          this.multipleSelectionKeys.push(list[i].id);
        }
      },
      handleFilter(params, done) {
        Object.assign(this.searchForm,params);
        this.search()
        done()
      },
    },
    mounted() {
      this.search();
      this.initLine();
      this.initReportNameIds();
    }
  }
</script>
<style lang="scss">

</style>
